package component.fulltextsearch.util;

import java.io.File;
import java.io.IOException;

import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;




public class IndexFactoryUtil {
	
	private static IndexFactoryUtil instance = null;
	
	private static final String DIR_PATH_NAME = "indexdir"; 
	
	private Directory dir = null;
	
	private IndexFactoryUtil () throws IOException {
		initDir();
	}
	private void initDir() throws IOException { 
		String dirPath = SearchConfigUtil.getInstance().getProperty(DIR_PATH_NAME);		
		dir = FSDirectory.getDirectory(dirPath);
	}
	
	public static IndexFactoryUtil getInstance() throws IOException {
		synchronized (DIR_PATH_NAME) {
			if (instance == null) {
				instance = new IndexFactoryUtil();
			}
		}
		return instance;
	}
	
	public IndexWriter getIndexWriter() throws IOException {
		if (dir == null)
			this.initDir();
		IndexWriter writer = new IndexWriter(dir,AnalyzerUtil.getAnalyzer(),MaxFieldLength.UNLIMITED);		
		return writer;
	}
	
	public IndexReader getIndexReader() throws IOException {
		if (dir == null)
			this.initDir();
		IndexReader reader = IndexReader.open(dir);
		return reader;
	}
	
	public IndexSearcher getIndexSearcher() throws IOException {
		if (dir == null)
			this.initDir();
		IndexSearcher searcher = new IndexSearcher(dir);
		return searcher;
	}
	
	public void closeWriter (IndexWriter writer ) throws Exception {
		try {
			writer.close();
		} finally {
			if (IndexWriter.isLocked(dir)) {
				IndexWriter.unlock(dir);
			}
		}
	}
	
	public void closeReader (IndexReader reader ) throws Exception {
		try {
			reader.close();
		} finally {
			if (IndexWriter.isLocked(dir)) {
				IndexWriter.unlock(dir);
			}
		}
	}

}
